<?php

declare (strict_types=1);
namespace app\admin\controller;

use app\admin\service\LoginLoggerService;
use app\admin\service\SysUserLoginService;
use app\admin\validate\LoginValidate;
use app\admin\logic\LoginLogic;
use app\common\model\admin\Admin;
use app\admin\logic\server\SettingLogic;
use SingKa\Sms\SkSms;
use think\facade\Config;
use app\common\model\server\Setting;
use \PHPMailer\PHPMailer\PHPMailer;
/**
 * 登录
 * Class Login
 * @package app\admin\controller\system
 */
class Login extends BaseAdmin
{

    public  function index()
    {
       return $this->success([]);
    }
    public function getSetting(){
        $data=SettingLogic::detail();
       
        return $this->success($data);
    }
    public function login()
    {
        //验证登录场景?
        $param  =$this->request->param();
       // validate(LoginValidate::class)->scene('scene_test')->check($param);
        $service = new SysUserLoginService();
        try {
            $sysUser = (new LoginLogic())->login($param);
            // 返回信息
            $result['userInfo'] =$sysUser;
            $result['auth'] = $service->auth($sysUser);
            $result['token'] = $service->createToken($sysUser);
            (new LoginLoggerService)->success($sysUser->username);
            cache($param['username'],'');
            return $this->success($result);
        }catch (Exception $e) {
            return $this->error($e->getMessage());
        }


    }
    //发送手机验证码
    public function sendcode(){
        $data = $this->request->post();
        $setting=Setting::find(1)->toArray();
        $res=$this->sendSms($data['mobile'],'login',[],$setting);
        return json($res);
    }
    /**
    * 短信发送示例
    *
    * @mobile  短信发送对象手机号码
    * @action  短信发送场景，会自动传入短信模板
    * @parme   短信内容数组
    */
    public function sendSms($mobile,$action,$parme,$setting)
    {
        $sms_default=$setting['sms_default'];
        $config=json_decode($setting['sms_config'],true)[$sms_default];
        $sms = new sksms($sms_default, $config,$mobile);//传入短信驱动和配置信息
        //判断短信发送驱动，非阿里云和七牛云，需将内容数组主键序号化
        if ($sms_default == 'aliyun') {
            $result = $sms->$action($mobile, $parme);
        } elseif ($sms_default == 'qiniu') {
            $result = $sms->$action([$mobile], $parme);
        } elseif ($sms_default == 'smsbao') {
            $result = $sms->$action($mobile, $parme);
        } else {
            $result = $sms->$action($mobile, $this->restoreArray($parme));
        }
        if ($result['code'] == 200) {
            $data['code'] = 200;
            $data['msg'] = '短信发送成功';
        } else {
            $data['code'] = $result['code'];
            $data['msg'] = $result['msg'];
        }
        return $data;
    }
  	
    /**
    * 数组主键序号化
    *
    * @arr  需要转换的数组
    */
    public function restoreArray($arr)
    {
        if (!is_array($arr)){
            return $arr;
        }
        $c = 0;
        $new = [];
        foreach ($arr as $key => $value) {
            $new[$c] = $value;
            $c++;
        }
        return $new;
    }
    //手机登录
    // public function phonelogin(){
        
    //     $param = $this->request->post();
    //     $user = Admin::where('username|phone|email', $param['phone'])->find();

    //     if (!$user) {
    //         return $this->error('无账户信息');
    //     }
    //     if ($user->status == 0) {
    //         return $this->error('账户已被禁用');
    //     }
    //     if($param['type']==0){ //验证码登录
    //         if($param['code']!=cache($param['phone'])){
    //             return $this->error('验证码错误');
    //         }
    //     }else if($param['type']==1){ //密码登录

    //         if (md5(md5($param['password'])) !== $user->password) {
    //             return $this->error('账户或密码错误');
    //         }
    //     }
    //     $service = new SysUserLoginService();
    //     try {
    //         // 返回信息
    //         // $result['userInfo'] = $service->userInfo($user);
    //         // $result['auth'] = $service->auth($user);
    //         // $result['token'] = $service->generateToken($user);
    //         // $result['ismobile']=Request::isMobile();
    //         $param['username']=$param['phone'];
    //         $param['password']=md5($param['password']);
    //         $sysUser = (new LoginLogic())->login($param);
    //         // 返回信息
    //         $result['userInfo'] =$sysUser;
    //         $result['auth'] = $service->auth($sysUser);
    //         $result['token'] = $service->createToken($sysUser);
    //         //生成任务
    //         //$this->subtask();
    //         //LoginLog::success($user->username);
            
    //         return $this->success($result);
    //     } catch (TipsException $e) {
    //         LoginLog::fail($param['phone'], $e->getMessage());
    //         return $this->error($e->getMessage(), $e->getCode());
    //     } catch (Exception $e) {
    //         LoginLog::fail($param['phone'], $e->getMessage());
    //         return $this->error($e->getMessage());
    //     }
    // }
    //发送邮箱验证码
    public function sendEmail(){
        $data = $this->request->post();
        $setting=Setting::find(1)->toArray();
        $subject='['.$setting['name'].']'.'验证码接收';
        $code = rand(1000, 9999);
        if (cache($data['email'])) {
            $data['code'] = 200;
            $data['msg'] = '已发送';
            return $data;
        }
        $title = '恭喜，验证码已收到';
        $content = $title . '【' . $code . '】。';//邮件内容
        $res=$this->send_mail($data['email'], $setting, $subject, $content, null);
        if ($res) {
            cache($data['email'], $code, 300);
            $data['code'] = 200;
            $data['msg'] = '发送成功';
        } else {
            $data['code'] = 0;
            $data['msg'] = '发送失败';
        }
        return $data;
    }
    function send_mail($tomail, $setting, $subject = '', $body = '', $attachment = null){
        $config=json_decode($setting['email_config'],true);
        $mail = new PHPMailer();             //实例化PHPMailer对象
        $mail->CharSet = 'UTF-8';           //设定邮件编码，默认ISO-8859-1，如果发中文此项必须设置，否则乱码
        $mail->IsSMTP();                    // 设定使用SMTP服务
        $mail->SMTPDebug = 0;               // SMTP调试功能 0=关闭 1 = 错误和消息 2 = 消息
        $mail->SMTPAuth = true;             // 启用 SMTP 验证功能
        $mail->SMTPSecure =$config['mail_verify_type']==1 ? 'ssl' : 'tls';          // 使用安全协议
        $mail->Host = $config['mail_smtp_host']; // SMTP 服务器
        $mail->Port = $config['mail_smtp_port'];                  // SMTP服务器的端口号
        $mail->Username = $config['mail_smtp_user'];    // SMTP服务器用户名
        $mail->Password = $config['mail_smtp_pass'];      // SMTP服务器密码，这里是你开启SMTP服务时生成密码
        $mail->From = $config['mail_from']; //发件人地址（也就是你的邮箱地址）
        $mail->FromName = $setting['name']; //发件人姓名
        $replyEmail = '';                   //留空则为发件人EMAIL
        $replyName = '';                    //回复名称（留空则为发件人名称）
        $mail->IsHTML(true); // 是否HTML格式邮件
        $mail->AddReplyTo($replyEmail, $replyName);
        $mail->Subject = $subject;
        $mail->MsgHTML($body);
        $mail->AddAddress($tomail, $setting['name']);
        if ($attachment !== null && is_file($attachment)) {
            // 尝试添加附件
            if ($mail->addAttachment($attachment)) {
                echo "附件添加成功";
            } else {
                echo "附件添加失败";
            }
        }
        return $mail->Send() ? true : $mail->ErrorInfo;
    }
}

